package com.ypz.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ypz.reggie.common.CustomException;
import com.ypz.reggie.common.R;
import com.ypz.reggie.dto.DishDto;
import com.ypz.reggie.entity.Category;
import com.ypz.reggie.entity.Dish;
import com.ypz.reggie.entity.DishFlavor;
import com.ypz.reggie.service.CategoryService;
import com.ypz.reggie.service.DishFlavorService;
import com.ypz.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 菜品和口味的管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
@Api(tags = "菜单接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "菜品名称",required = false)
    })
    public R<Page> page(int page, int pageSize, String name) {

        // 因为没有前端需要的categoryName所以需要用到DishDto
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        //查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //执行查询数据库之后，dishPage里面就自动将返回的值封装了
        dishService.page(dishPage, lqw);

        //将除了record的其他属性拷贝到dishDtoPage，其他属性是指总条数，当前页数等等
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //拿到dishPage里的records
        List<Dish> dishPageRecords = dishPage.getRecords();
        //这里的dishDtoPageRecords为空
        List<DishDto> dishDtoPageRecords = new ArrayList<>();

        //根据拿到dishPageRecords的record的CategoryId，查询数据库的category，得到里面的name
        for (Dish dishPageRecord : dishPageRecords) {
            //拿到dishPageRecords的record的CategoryId
            Long categoryId = dishPageRecord.getCategoryId();

            //查询数据库的category
           Category category = categoryService.getById(categoryId);

            //得到里面的name
            String categoryName = category.getName();

            DishDto dishDto = new DishDto();

            //将dishPageRecord的数据复制到dishDto
            BeanUtils.copyProperties(dishPageRecord, dishDto);

            //设置dishDto的CategoryName属性
            dishDto.setCategoryName(categoryName);

            //将dishDro放入dishDtoPageRecords
            dishDtoPageRecords.add(dishDto);
        }

        //设置dishDtoPage的records
        dishDtoPage.setRecords(dishDtoPageRecords);

        return R.success(dishDtoPage);
    }

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //注意：keys支持通配符，delete不支持通配符
        //清除所有的，菜品信息的缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //清理某个分类下的缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        Boolean delete = redisTemplate.delete(key);

        return R.success("保存成功");
    }

    /**
     * 根据id查找菜品和对应的口味
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {

        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);

        return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> modify(@RequestBody DishDto dishDto) {

        dishService.modifyWithFlavor(dishDto);
        //注意：keys支持通配符，delete不支持通配符
        //清除所有的，菜品信息的缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //清理某个分类下的缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }

//    /**
//     * 根据分类id查询菜品
//     * 为了增加通用性，用Dish接受
//     * @param dish
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        //为了保证代码的安全性，先判断是否为null
//        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
//        //查询状态为1的菜品，也就是起售的
//        lqw.eq(Dish::getStatus,1);
//        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        List<Dish> dishList = dishService.list(lqw);
//
//        return R.success(dishList);
//    }

    /**
     * 根据分类id查询菜品和口味
     * 为了增加通用性，用Dish接受
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        long l = System.currentTimeMillis();
        List<DishDto> dishDtos =null;
        //动态构造key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtos != null){
            //如果存在，直接返回，无需查找数据库
            long l2 = System.currentTimeMillis();
            System.out.println("查Redis："+(l2-l));
            return R.success(dishDtos);
        }

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //为了保证代码的安全性，先判断是否为null
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询状态为1的菜品，也就是起售的
        lqw.eq(Dish::getStatus, 1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(lqw);

        dishDtos = new ArrayList<>();

        //加上口味
        for (Dish dish1 : dishList) {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish1, dishDto);

            //菜品id
            Long id = dish1.getId();

            //更具菜品id查口味
            LambdaQueryWrapper<DishFlavor> lqwDishFlavor = new LambdaQueryWrapper<>();
            lqwDishFlavor.eq(DishFlavor::getDishId, id);

            List<DishFlavor> list = dishFlavorService.list(lqwDishFlavor);

            dishDto.setFlavors(list);

            dishDtos.add(dishDto);

        }

        //如果不存在，查询数据库之后，放入缓存
        redisTemplate.opsForValue().set(key,dishDtos,10l, TimeUnit.MINUTES);

        long l3 = System.currentTimeMillis();
        System.out.println("查数据库:"+(l3-l));
        return R.success(dishDtos);

    }

    /**
     * 修改菜品售卖状态
     * 停售、起售
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> modifyStatus(Long[] ids,@PathVariable Integer status){

        //减少使用服务器空间，但是增加了访问数据库次数
//        Dish dish = new Dish();
//
//        for (Long id : ids) {
//
//            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//            lqw.eq(id != null,Dish::getId,id);
//
//            dish.setStatus(status);
//
//            dishService.update(dish,lqw);
//        }

        //减少访问数据库次数，但是浪费了服务器空间
        List<Dish> dishList = new ArrayList<>();

        for (Long id : ids) {

            Dish dish = new Dish();
            dish.setStatus(status);
            dish.setId(id);

           dishList.add(dish);
        }

        boolean b = dishService.updateBatchById(dishList);

        if (b){
            return R.success("账号状态已改变");
        }

        return R.error("未知错误");
    }

    /**
     * 删除菜品，正在售卖中的不能删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){

        for (Long id : ids) {
            Dish dish = dishService.getById(id);

            if (dish.getStatus() == 1){
                throw new CustomException("菜品正在售卖中不能删除");
            }

        }

        dishService.removeByIds(ids);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("删除成功");
    }


}
